package org.chen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.chen.mapper.SysUserMapper;
import org.chen.model.admin.SysUser;
import org.chen.model.dto.UpdatePasswordDTO;
import org.chen.model.dto.UpdateProfileDTO;
import org.chen.service.ISecurityUserService;
import org.chen.utils.JwtTokenUtil;
import org.chen.utils.PasswordUtil;
import org.chen.utils.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISecurityUserService, UserDetailsService {

    private final SysUserMapper sysUserMapper;
    private final PasswordUtil passwordEncoder;

    public SysUserServiceImpl(SysUserMapper userMapper, PasswordUtil passwordEncoder) {
        this.sysUserMapper = userMapper;
        this.passwordEncoder = passwordEncoder;
    }

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private RedisService redisService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = this.selectByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        user.setRoles(this.selectUserRoles(user.getId()));
        return user;
    }

    @Override
    public SysUser selectByUsername(String username) {
        return sysUserMapper.selectOne(new QueryWrapper<SysUser>().eq("username",username));
    }

    @Override
    public List<String> selectUserRoles(Long id) {
        return sysUserMapper.selectUserRoles(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateProfile(UpdateProfileDTO profileDTO) {
        // 获取当前登录用户
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        SysUser user = this.selectByUsername(username);

        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 更新用户信息
        SysUser updateUser = new SysUser();
        updateUser.setId(user.getId());
        updateUser.setNickname(profileDTO.getNickname());
        updateUser.setEmail(profileDTO.getEmail());

        if (this.updateById(updateUser)) {
            // 更新成功，清除redis中的用户信息缓存
            String userCacheKey = "user:info:" + username;
            redisService.del(userCacheKey);
        } else {
            throw new RuntimeException("更新个人信息失败");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updatePassword(UpdatePasswordDTO passwordDTO) {
        // 获取当前登录用户
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        SysUser user = this.selectByUsername(username);

        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 验证旧密码
        if (!passwordEncoder.matches(passwordDTO.getOldPassword(), user.getPassword())) {
            throw new RuntimeException("原密码不正确");
        }

        // 验证两次密码是否一致
        if (!passwordDTO.getNewPassword().equals(passwordDTO.getConfirmPassword())) {
            throw new RuntimeException("两次输入的密码不一致");
        }

        // 更新密码
        SysUser updateUser = new SysUser();
        updateUser.setId(user.getId());
        updateUser.setPassword(passwordEncoder.encode(passwordDTO.getNewPassword()));

        if (this.updateById(updateUser)) {
            // 更新成功，清除redis中的token和用户信息
            String tokenKey = "token:" + username;
            String userCacheKey = "user:info:" + username;
            redisService.del(tokenKey, userCacheKey);
        } else {
            throw new RuntimeException("修改密码失败");
        }
    }

    @Override
    public String login(String username, String password) {
        UserDetails userDetails = loadUserByUsername(username);
        if (!passwordEncoder.matches(password, userDetails.getPassword())) {
            throw new BadCredentialsException("密码不正确");
        }
        String token = jwtTokenUtil.generateToken(userDetails);
        // 将token存入redis
        String tokenKey = "token:" + username;
        redisService.set(tokenKey, token, jwtTokenUtil.getExpiration());
        return token;
    }

    @Override
    public void logout(String username) {
        String tokenKey = "token:" + username;
        redisService.del(tokenKey);
    }
}
